package com.loadmore.common;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.loadmore.common.db.DaoOpenHelper;
import com.loadmore.common.db.gen.DaoMaster;
import com.loadmore.common.db.gen.DaoSession;
import com.loadmore.common.util.InitUtil;
import com.loadmore.common.util.LogUtil;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.util.Stack;



/**
 * @author sunleilei
 * @date 2017/5/14
 */

public class App extends Application {
    public static App application;
    private static Stack<Activity> activities = new Stack<>();
    private static DaoSession daoSession;
    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        init();

    }

    public void init() {
        InitUtil.initScreen(this);
        setupDatabase();
        ZXingLibrary.initDisplayOpinion(this);
    }

    public static App getApplication() {
        return application;
    }

    public void addActivity(Activity activity) {
        activities.push(activity);
    }

    public void removeActivity() {
        activities.pop();
    }

    /**
     * 配置数据库
     */
    private void setupDatabase() {
        //创建数据库shop.db"
        DaoOpenHelper helper = new DaoOpenHelper(this, "loadmore.db", null);
        //获取可写数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        //获取数据库对象
        DaoMaster daoMaster = new DaoMaster(db);
        //获取Dao对象管理者
        daoSession = daoMaster.newSession();
    }

    public static DaoSession getDao() {
        return daoSession;
    }

    public int getActivityCount() {
        return activities.size();
    }

    public void exitApp() {
        for (int i = 0; i < activities.size(); i++) {
            Activity activity = activities.get(i);
            activity.finish();
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        LogUtil.e("onLowMemory");
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        LogUtil.e("onTerminate");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        LogUtil.e("onTrimMemory "+level);
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }
}
